package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file){
        try{
            if (file==null){
                throw new RuntimeException("文件不存在");
            }
            //原始名称
            String filename = file.getOriginalFilename();
            if (filename==null || "".equals(filename)){
                throw new RuntimeException("文件不存在");
            }
            //文件内容
            byte[] content = file.getBytes();
            //拓展名 123.456.txt
            String ext = filename.substring(filename.lastIndexOf(".") + 1);
            /**
             *
             * @param name 文件名字
             * @param content   文件内容
             * @param ext   文件扩展名
             */
            FastDFSFile fastDFSFile = new FastDFSFile(filename,content,ext);
            //2工具类fastdfsClient upload上传方法
            String[] upload = FastDFSClient.upload(fastDFSFile);
            System.out.println(upload);
            //组名
            String group = upload[0];
            //文件路径
            String path = upload[1];

            //正真访问路径
            //http://127.0.0.1/group1/M00/00/00/23123dsdfgaga.txt
            String result = FastDFSClient.getTrackerUrl() + group + "/" + path;

            //3构建Result对象
            return new Result(true,StatusCode.OK,"上传成功",result);

        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR,"文件上传失败");
    }
}
